﻿@{
    ViewData["Title"] = "职级管理";
    Layout = null;
}

<link href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<script src="~/libs/jquery/jquery.js"></script>
<script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>

<div style="padding:20px;">
    <form class="layui-form" id="searchForm" style="margin-bottom: 10px;display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
        <div class="layui-form-item" style="margin-bottom:0;">
            <label class="layui-form-label">职级编码</label>
            <div class="layui-input-inline" style="width:180px;">
                <input type="text" name="JobGradeCoding" placeholder="请输入职级编码" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" style="margin-bottom:0;">
            <label class="layui-form-label">职级层次</label>
            <div class="layui-input-inline" style="width:180px;">
                <input type="text" name="JobGradeLevel" placeholder="请输入职级层次" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" style="margin-bottom:0;">
            <label class="layui-form-label">职级层次名称</label>
            <div class="layui-input-inline" style="width:180px;">
                <input type="text" name="JobGradeLevelName" placeholder="请输入职级层次名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" style="margin-bottom:0;">
            <label class="layui-form-label">薪资范围</label>
            <div class="layui-input-inline" style="width:120px;">
                <input type="number" name="SalaryRangelower" placeholder="请输入下限" autocomplete="off" class="layui-input">
            </div>
            <span style="margin:0 5px;">~</span>
            <div class="layui-input-inline" style="width:120px;">
                <input type="number" name="SalaryRangelimits" placeholder="请输入上限" autocomplete="off" class="layui-input">
            </div>
        </div>
        <button class="layui-btn" lay-submit lay-filter="search">搜索</button>
        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
    </form>
    <button class="layui-btn" id="btnAdd">新增</button>
    <button class="layui-btn layui-btn-warm" id="btnExport" type="button">导出</button>
    <button class="layui-btn layui-btn-danger" id="btnBatchDelete" type="button">批量删除</button>
 
    <table class="layui-hide" id="jobGradeTable" lay-filter="jobGradeTable"></table>
</div>
<iframe id="downloadFrame" style="display:none;"></iframe>

<!-- 新增弹窗表单内容，直接用div隐藏 -->
<div id="addFormDiv" style="display:none;">
    @Html.AntiForgeryToken()
    <form class="layui-form" lay-filter="addForm" style="padding:20px;">
        <div class="layui-form-item">
            <label class="layui-form-label">职级编码</label>
            <div class="layui-input-block">
                <input type="text" name="JobGradeCoding" required lay-verify="required" placeholder="请输入职级编码" autocomplete="off" class="layui-input" readonly disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">职级层次</label>
            <div class="layui-input-block">
                <input type="text" name="JobGradeLevel" required lay-verify="required" placeholder="请输入职级层次" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">职级层次名称</label>
            <div class="layui-input-block">
                <input type="text" name="JobGradeLevelName" required lay-verify="required" placeholder="请输入职级层次名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">薪资范围下限</label>
            <div class="layui-input-block">
                <input type="number" name="SalaryRangelower" required lay-verify="required|number" placeholder="请输入薪资范围下限" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">薪资范围上限</label>
            <div class="layui-input-block">
                <input type="number" name="SalaryRangelimits" required lay-verify="required|number" placeholder="请输入薪资范围上限" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <input type="text" name="ReferenceColumn" placeholder="请输入备注" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="submitAdd">确定</button>
                <button type="button" class="layui-btn layui-btn-primary" id="cancelAdd">取消</button>
            </div>
        </div>
    </form>
</div>

<!-- 操作列模板 -->
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script>
    $(function(){
        layui.use(['table', 'form', 'layer'], function () {
            var table = layui.table, form = layui.form, layer = layui.layer;

            var tableIns = table.render({
                elem: '#jobGradeTable',
                url: '/HumanResources/GetJobGradeTableData',
                method: 'get',
                page: true,
                where: {}, // 初始无条件
                request: {
                    pageName: 'PageIndex', // 页码的参数名称，默认：page
                    limitName: 'PageSize'  // 每页数据量的参数名，默认：limit
                },
                cols: [[
                    { type: 'checkbox' },
                    { field: 'jobGradeCoding', title: '职级编码' },
                    { field: 'jobGradeLevel', title: '职级层次' },
                    { field: 'jobGradeLevelName', title: '职级层次名称' },
                    { field: 'salaryRangelower', title: '薪资范围下限' },
                    { field: 'salaryRangelimits', title: '薪资范围上限' },
                    { field: 'referenceColumn', title: '备注' },
                    { title: '操作', toolbar: '#barDemo' }
                ]]
            });

            // 搜索按钮事件
            form.on('submit(search)', function(data){
                tableIns.reload({
                    where: data.field,
                    page: {curr: 1}
                });
                return false;
            });

            // 重置按钮事件
            $('#searchForm')[0].reset = function() {
                tableIns.reload({where: {}, page: {curr: 1}});
            };

            // 新增按钮
            $('#btnAdd').off('click').on('click', function () {
                var snowflakeId = generateSnowflakeId();
                $("input[name='JobGradeCoding']").val(snowflakeId); // 直接赋值到输入框
                form.val('addForm', {
                    "JobGradeCoding": snowflakeId,
                    "JobGradeLevel": "",
                    "JobGradeLevelName": "",
                    "SalaryRangelower": "",
                    "SalaryRangelimits": "",
                    "ReferenceColumn": ""
                });
                $('#addFormDiv').removeData('edit-id'); // 新增时清除编辑标记
                layer.open({
                    type: 1,
                    title: '添加职级管理',
                    area: ['600px', '500px'],
                    content: $('#addFormDiv'),
                    end: function () {
                        $('#addFormDiv').hide();
                    }
                });
            });

            // 雪花ID生成函数
            function generateSnowflakeId() {
                // 简单雪花算法实现（时间戳+随机数）
                return Date.now().toString() + Math.floor(Math.random()*1000).toString();
            }

            // 取消按钮
            $('#cancelAdd').off('click').on('click', function () {
                layer.closeAll();
            });

            // 监听表格工具条事件，处理删除和编辑
            table.on('tool(jobGradeTable)', function(obj){
                var data = obj.data;
                if(obj.event === 'del'){
                    layer.confirm('是否确认删除所选职级管理的数据项？', {
                        title: '系统提示',
                        btn: ['确定', '取消'],
                        btn1: function(index, layero){
                            $.ajax({
                                url: '/HumanResources/DelJobGradeManagement',
                                type: 'delete',
                                data: { id: data.id ,__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()},
                                success: function(res){
                                    alert('删除成功');
                                    obj.del(); // 前端移除行
                                }
                            });
                            layer.close(index);
                        }
                    });
                } else if(obj.event === 'edit') {
                    // 编辑逻辑
                    $.get('/HumanResources/GetJobGradeManagementModel', { id: data.id }, function(res) {
                        // 回显数据到表单
                        form.val('addForm', {
                            JobGradeCoding: res.jobGradeCoding,
                            JobGradeLevel: res.jobGradeLevel,
                            JobGradeLevelName: res.jobGradeLevelName,
                            SalaryRangelower: res.salaryRangelower,
                            SalaryRangelimits: res.salaryRangelimits,
                            ReferenceColumn: res.referenceColumn
                        });
                        $("input[name='JobGradeCoding']").val(res.jobGradeCoding); // 确保禁用框也显示
                        layer.open({
                            type: 1,
                            title: '编辑职级管理',
                            area: ['600px', '500px'],
                            content: $('#addFormDiv'),
                            end: function () {
                                $('#addFormDiv').hide();
                            }
                        });
                        // 标记为编辑
                        $('#addFormDiv').data('edit-id', res.id);
                    });
                }
            });

            // 提交表单
            form.on('submit(submitAdd)', function (data) {
                var lower = Number(data.field.SalaryRangelower);
                var upper = Number(data.field.SalaryRangelimits);
                if (upper < lower) {
                    layer.msg('薪资范围上限不能小于下限！');
                    return false;
                }
                var editId = $('#addFormDiv').data('edit-id');
                var postData = {
                    Id: editId || 0,
                    JobGradeCoding: data.field.JobGradeCoding,
                    JobGradeLevel: data.field.JobGradeLevel,
                    JobGradeLevelName: data.field.JobGradeLevelName,
                    ReferenceColumn: data.field.ReferenceColumn,
                    SalaryRangelower: lower,
                    SalaryRangelimits: upper,
                    __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                };
                var url = editId ? '/HumanResources/UpJobGradeManagement' : '/HumanResources/AddJobGradeManagementModel';
                var type = editId ? 'PUT' : 'POST';
                $.ajax({
                    url: url,
                    type: type,
                    data: postData,
                    dataType: 'json',
                    async: false,
                    success: function (res) {
                        if ((editId && res > 0) || (!editId && res > 0)) {
                            layer.msg(editId ? '修改成功' : '添加成功');
                            layer.closeAll();
                            location.reload();
                        } else {
                            layer.msg(res.msg || (editId ? '修改失败' : '添加失败'));
                        }
                    }
                });
                // 清除编辑标记
                $('#addFormDiv').removeData('edit-id');
                return false;
            });

            // 导出按钮事件
            $('#btnExport').off('click').on('click', function () {
                var page = tableIns.config.page.curr;
                var limit = tableIns.config.page.limit;
                var where = tableIns.config.where || {};
                var params = $.param(Object.assign({}, where, { PageIndex: page, PageSize: limit }));
                $('#downloadFrame').attr('src', '/HumanResources/ExportExcel?' + params);
            });

            // 批量删除按钮事件
            $('#btnBatchDelete').off('click').on('click', function () {
                var checkStatus = table.checkStatus('jobGradeTable');
                var data = checkStatus.data;
                if (data.length === 0) {
                    layer.msg('请先选择要删除的数据');
                    return;
                }
                var ids = data.map(function (item) { return item.id; });
                layer.confirm('确定要批量删除选中的数据吗？', { title: '系统提示', btn: ['确定', '取消'] }, function (index) {
                    $.ajax({
                        url: '/HumanResources/BatchDelJobGradeManagement',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(ids),
                        headers: {
                            'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                        },
                        success: function (res) {
                            layer.msg('批量删除成功');
                            tableIns.reload();
                        },
                        error: function (xhr) {
                            layer.msg('批量删除失败');
                        }
                    });
                    layer.close(index);
                });
            });
        });
    });
</script>